import fs from 'fs'
import watch from 'node-watch'
import {httpPost} from "./httpClient.js";

const {LOG_ERROR_PATH} = process.env


/**
 * @author: ares
 * @date: 2023/3/31 22:50
 * @description: 获取最新错误日志
 * @param{string} filename
 */
function getLatestError(filename) {
	return new Promise((resolve, reject) => {
		fs.readFile(filename, 'utf8', (error, data) => {
			if (error) return
			let dataArray = data.split(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3})/),
				err = dataArray.pop(),
				date = dataArray.pop();
			resolve(`${date} [ ${filename} ]${err}`)
		})
	})
}


/**
 * @author: ares
 * @date: 2023/4/1 9:05
 * @description: 监测者
 */
// @ts-ignore
const watcher = watch(LOG_ERROR_PATH, {recursive: true});

/**
 * @author: ares
 * @date: 2023/4/1 9:41
 * @description: 监测日志文件变化
 */
watcher.on('change', function (evt, filename: string) {
	if (!filename || !/\.log$/.test(filename)) return;
	getLatestError(filename).then(msg => {
		console.log(msg)
	}).catch(err=>{})
});


export default watcher;
